<template>
  <question-detail 
    :question="question"
    :current-question-index="currentQuestionIndex"
    :question-list="questionList"
    :is-collected="isCollected"
    :is-mastered="isMastered"
    @goToPrevQuestion="goToPrevQuestion"
    @goToNextQuestion="goToNextQuestion"
    @toggleCollect="toggleCollect"
    @toggleMastered="markAsMastered"
    @goToAskAI="goToAskAI"
  />
</template>

<script>
import QuestionDetail from '@/components/question-detail.vue';
import DifficultyTag from '@/components/difficulty-tag.vue';
import UaMarkdown from '@/components/ua2-markdown/ua-markdown.vue';
import config from '@/common/config.js';

export default {
  components: {
    QuestionDetail,
    DifficultyTag,
    UaMarkdown
  },
  data() {
    return {
      question: {
        id: 1,
        title: '',
        categoryName: '',
        difficulty: '★★★',
        views: 0,
        description: '',
        answer: '',
        tags: []
      },
      isCollected: false,
      isMastered: false,
      currentQuestionIndex: 0,
      questionList: [],
      questionId: null,
      categoryId: null,
      filterMastered: uni.getStorageSync('filterMastered') !== false // 从localStorage读取过滤设置，默认为true
    };
  },
  
  computed: {
    hasPrev() {
      return this.currentQuestionIndex > 0;
    },
    hasNext() {
      return this.currentQuestionIndex < this.questionList.length - 1;
    }
  },
  
  onLoad(options) {
    console.log("当前页面参数:", options);
    this.questionId = options.questionId;
    this.categoryId = options.categoryId;
    // 如果有categoryId和questionId，则通过接口获取问题详情
    this.loadQuestionsByCategory();
  },
  
  methods: {
    // 根据分类ID加载问题列表
    loadQuestionsByCategory() {
      this.$request(`/interview/question/listWithStatus?categoryId=${this.categoryId}`, 'GET')
        .then(res => {
          if (res.code === 200) {
            // 保存问题列表
            this.questionList = res.rows;
            
            // 根据开关状态决定是否过滤已掌握的题目
            if (this.filterMastered) {
              this.questionList = this.questionList.filter(item => !item.isMastered || item.isMastered !== 1);
            }
            
            // 根据questionId查找当前问题
            const currentIndex = this.questionList.findIndex(q => q.questionId == this.questionId);
            if (currentIndex !== -1) {
              this.currentQuestionIndex = currentIndex;
              this.setQuestionDetailFromApi(this.questionList[currentIndex]);
              // 从新接口直接获取收藏和掌握状态
              this.isCollected = this.questionList[currentIndex].isFavorite === 1;
              this.isMastered = this.questionList[currentIndex].isMastered === 1;
            } else {
              // 如果没找到对应的问题，默认显示第一个
              this.currentQuestionIndex = 0;
              if (this.questionList.length > 0) {
                this.setQuestionDetailFromApi(this.questionList[0]);
                // 从新接口直接获取收藏和掌握状态
                this.isCollected = this.questionList[0].isFavorite === 1;
                this.isMastered = this.questionList[0].isMastered === 1;
              }
            }
          }
        }).catch(err => {
          console.error('获取问题列表异常:', err);
        });
    },
    
    // 根据API返回的数据设置问题详情
    setQuestionDetailFromApi(questionData) {
      this.question = {
        id: questionData.questionId,
        title: questionData.content || '暂无标题',
        category: questionData.categoryName || this.question.category,
        difficulty: questionData.difficulty || '中等',
        views: questionData.views || 0,
        answer: questionData.analysis || '暂无答案',
        categoryName: questionData.categoryName || '',
        tags: []
      };
    },
    
    setCurrentQuestionIndex() {
      // 根据当前题目标题设置索引
      this.currentQuestionIndex = this.questionList.findIndex(
        title => title === this.question.title
      );
      
      // 如果未找到，默认为第一个
      if (this.currentQuestionIndex === -1) {
        this.currentQuestionIndex = 0;
      }
    },
    

    goToPrevQuestion() {
      if (this.hasPrev) {
        let newIndex = this.currentQuestionIndex - 1;
        
        // 如果开启了过滤已掌握题目，则跳过已掌握的题目
        while (newIndex >= 0 && this.filterMastered && this.questionList[newIndex].isMastered === 1) {
          newIndex--;
        }
        
        // 如果找到有效题目
        if (newIndex >= 0) {
          this.currentQuestionIndex = newIndex;
          if (this.categoryId) {
            // 从API获取的数据
            this.setQuestionDetailFromApi(this.questionList[this.currentQuestionIndex]);
            // 从新接口直接获取收藏和掌握状态
            this.isCollected = this.questionList[this.currentQuestionIndex].isFavorite === 1;
            this.isMastered = this.questionList[this.currentQuestionIndex].isMastered === 1;
          } else {
            // 从默认数据获取
            this.question.title = this.questionList[this.currentQuestionIndex];
            this.setQuestionDetail();
          }
          // 滚动到页面头部
          uni.pageScrollTo({
            scrollTop: 0,
            duration: 300
          });
        } else {
          // 没有更多未掌握的题目
          uni.showToast({
            title: '前面没有更多未掌握的题目',
            icon: 'none'
          });
        }
      }
    },
    
    goToNextQuestion() {
      if (this.hasNext) {
        let newIndex = this.currentQuestionIndex + 1;
        
        // 如果开启了过滤已掌握题目，则跳过已掌握的题目
        while (newIndex < this.questionList.length && this.filterMastered && this.questionList[newIndex].isMastered === 1) {
          newIndex++;
        }
        
        // 如果找到有效题目
        if (newIndex < this.questionList.length) {
          this.currentQuestionIndex = newIndex;
          if (this.categoryId) {
            // 从API获取的数据
            this.setQuestionDetailFromApi(this.questionList[this.currentQuestionIndex]);
            // 从新接口直接获取收藏和掌握状态
            this.isCollected = this.questionList[this.currentQuestionIndex].isFavorite === 1;
            this.isMastered = this.questionList[this.currentQuestionIndex].isMastered === 1;
          } else {
            // 从默认数据获取
            this.question.title = this.questionList[this.currentQuestionIndex];
            this.setQuestionDetail();
          }
          // 滚动到页面头部
          uni.pageScrollTo({
            scrollTop: 0,
            duration: 300
          });
        } else {
          // 没有更多未掌握的题目
          uni.showToast({
            title: '后面没有更多未掌握的题目',
            icon: 'none'
          });
        }
      }
    },
    
    toggleCollect() {
      // 切换收藏状态
      const newCollectState = !this.isCollected;
      
      if (newCollectState) {
        // 添加收藏
        this.$request('/interview/favorite/add', 'POST', {
          questionId: this.question.id
        },{'content-type': 'application/json'}).then(res => {
          if (res.code === 200) {
            this.isCollected = newCollectState;
            // 同时更新题目列表中的状态
            const currentQuestion = this.questionList.find(q => q.questionId == this.question.id);
            if (currentQuestion) {
              currentQuestion.isFavorite = 1;
            }
            uni.showToast({
              title: '已收藏',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: '收藏失败',
              icon: 'none'
            });
          }
        }).catch(err => {
          console.error('收藏失败:', err);
          uni.showToast({
            title: '收藏失败',
            icon: 'none'
          });
        });
      } else {
        // 取消收藏
        this.$request('/interview/favorite/remove/' + this.question.id, 'DELETE')
          .then(res => {
            if (res.code === 200) {
              this.isCollected = newCollectState;
              // 同时更新题目列表中的状态
              const currentQuestion = this.questionList.find(q => q.questionId == this.question.id);
              if (currentQuestion) {
                currentQuestion.isFavorite = 0;
              }
              uni.showToast({
                title: '已取消收藏',
                icon: 'success'
              });
            } else {
              uni.showToast({
                title: '取消收藏失败',
                icon: 'none'
              });
            }
          }).catch(err => {
            console.error('取消收藏失败:', err);
            uni.showToast({
              title: '取消收藏失败',
              icon: 'none'
            });
          });
      }
    },
    
    // 标记为已掌握功能
    markAsMastered() {
      // 切换掌握状态
      const newMasteredState = !this.isMastered;
      
      if (newMasteredState) {
        // 添加掌握记录
        this.$request('/interview/mastered/add', 'POST', {
          questionId: this.question.id
        }, {'content-type': 'application/json'}).then(res => {
          if (res.code === 200) {
            this.isMastered = newMasteredState;
            // 同时更新题目列表中的状态
            const currentQuestion = this.questionList.find(q => q.questionId == this.question.id);
            if (currentQuestion) {
              currentQuestion.isMastered = 1;
            }
            uni.showToast({
              title: '标记为已掌握',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: '标记失败',
              icon: 'none'
            });
          }
        }).catch(err => {
          console.error('标记掌握失败:', err);
          uni.showToast({
            title: '标记失败',
            icon: 'none'
          });
        });
      } else {
        // 取消掌握状态（如果需要此功能）
        // 这里暂不实现取消掌握功能，因为通常掌握是单向操作
        uni.showToast({
          title: '已掌握不能取消',
          icon: 'none'
        });
        return;
      }
    },
    
    // 跳转到AI问答页面
    goToAskAI() {
      uni.navigateTo({
        url: `/pages/askai/detail?title=${encodeURIComponent(this.question.title)}`
      });
    },
    
    shareQuestion() {
      uni.showToast({
        title: '分享功能开发中',
        icon: 'none'
      });
    },
    
    setQuestionDetail() {
      // 空实现，保持兼容性
    }
  }
};
</script>

<style>
.container {
  background: linear-gradient(135deg, #ffffff 0%, #e6e6e6 100%);
  min-height: 100vh;
  padding: 15px;
  padding-bottom: 120px;
}

.question-header {
  background-color: #fff;
  border-radius: 10px;
  padding: 10px;
  margin-bottom: 15px;
}

.question-title {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}

.question-meta {
  display: flex;
  flex-wrap: wrap;
  font-size: 14px;
  color: #999;
}

.meta-item {
  background-color: #f0f0f0;
  padding: 5px 10px;
  border-radius: 5px;
  margin-right: 10px;
  margin-bottom: 5px;
}

.question-content {
  background-color: #fff;
  border-radius: 10px;
  padding: 10px;
}

.content-section {
  margin-bottom: 25px;
}

.content-section:last-child {
  margin-bottom: 0;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.section-content {
  font-size: 15px;
  color: #666;
  line-height: 1.6;
}

.section-content.answer {
  background-color: #fdfdfd;
  padding: 0px;
  border-radius: 5px;
}

.tags {
  display: flex;
  flex-wrap: wrap;
}

.tag {
  background-color: var(--primary-light-color);
  color: var(--primary-color);
  padding: 5px 10px;
  border-radius: 5px;
  margin-right: 10px;
  margin-bottom: 10px;
  font-size: 14px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  position: fixed;
  bottom: 0px;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 10px 15px 30px;
}

.nav-icons {
  display: flex;
  align-items: center;
}

.nav-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 5px;
}

.nav-icon.disabled {
  opacity: 0.5;
}

.center-icons {
  display: flex;
  align-items: center;
  width: 50%;
  justify-content: center;
}

.ai-icon {
  width: fit-content;
  height: 40px;
  padding: 0px 20px;
  border-radius: 20px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: -1px 9px 19px 9px #8484840d
}

.ai-icon img {
  height: 18px;
  width: 55px;
}

.action-icons {
  display: flex;
}

.action-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 5px;
}
</style>